//
//  XHF_BaseViewController.m
//  haojia
//
//  Created by 徐宏飞 on 16/4/11.
//  Copyright © 2016年 徐宏飞. All rights reserved.
//

#import "XHF_BaseViewController.h"
#import "XHF_LeftView.h"
#import "SearchTextField.h"

//#import "BaseTableViewController.h"



#define kScreenHeight [[UIScreen mainScreen] bounds].size.height
#define kScreenWidth [[UIScreen mainScreen] bounds].size.width

@interface XHF_BaseViewController () <UITextFieldDelegate,UISearchResultsUpdating,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchControllerDelegate>
@property(nonatomic,strong)NSMutableArray *dataList;
@property(nonatomic,strong)NSMutableArray *searchList;
@property(nonatomic,retain)UISearchController *searchController;//搜索控制器
@property(nonatomic,retain) UITableViewController *searchTableViewController;//搜索控制器初始化时的搜索结果控制器
@property(nonatomic,retain)UICollectionView *addressCollectionView;//有数据时的collectionView
@property(nonatomic,retain)UIImageView *bgView; //背景view
@property(nonatomic,assign)NSString *returnText;
@property(nonatomic,retain)UISearchBar *searchBar;

@end

@implementation XHF_BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createNavigationBack];
    [self createNavigationUI];
    [self initData];
}
- (void)initData
{
    _dataList = [NSMutableArray array];
    _searchList = [NSMutableArray array];
    self.dataList=[NSMutableArray arrayWithCapacity:30];
    
    //产生100个“数字+三个随机字母”
    for (NSInteger i=0; i<30; i++) {
        [self.dataList addObject:[NSString stringWithFormat:@"%ld%@",(long)i,[self shuffledAlphabet]]];
    }
}
- (void)createNavigationBack{
    
    //  Subclass TODO

}

- (void)createNavigationUI
{
    //返回按钮
    if (self.enableReturnButton) {
        
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrowOrange"] style:UIBarButtonItemStyleDone target:self action:@selector(handleBack)];
        leftItem.tintColor = [UIColor orangeColor];
        self.navigationItem.leftBarButtonItem = leftItem;
    }
    
    self.textField = [[SearchTextField alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth-50, 36)];
    _textField.delegate = self;
    self.navigationItem.titleView = _textField;
    
    //设置输入框的占位符
    _textField.placeholder = @"设计风格/设计师";
}


#pragma mark - UITableView代理方法
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    // 创建出搜索使用的表示图控制器
    self.searchTableViewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    _searchTableViewController.tableView.dataSource = self;
    _searchTableViewController.tableView.delegate = self;
    _searchTableViewController.tableView.tableFooterView = [UIView new];
    
    
   
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchTableViewController];
    //搜索框检测代理
    //（这个需要遵守的协议是 <UISearchResultsUpdating> ，这个协议中只有一个方法，当搜索框中的值发生变化的时候，代理方法就会被调用）
    _searchController.searchResultsUpdater = self;
    _searchController.searchBar.delegate = self;
    _searchController.hidesNavigationBarDuringPresentation = NO;     //是否隐藏导航栏
    _searchController.searchBar.placeholder = @"设计风格/设计师";
    _searchController.searchBar.tintColor = [UIColor redColor];
    [_searchController.searchBar setBarTintColor:[UIColor redColor]];
    _searchController.view.backgroundColor = [UIColor whiteColor];
    
  
    
    
    //弹出模态视图
    [self presentViewController:self.searchController animated:YES completion:^{
        nil;
    }];
    
   
    return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_searchList.count) {
        return [self.searchList count];
    }
    return 1;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
    if(!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseIdentifier"];
    }
    if (_searchList.count) {
        for (UIView * view in cell.contentView.subviews) {
            [view removeFromSuperview];
        }
        cell.textLabel.text = self.searchList[indexPath.row];
    }else{
        UIImageView *bgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64)];
        bgView.image = [UIImage imageNamed:@"hdv"];
        [cell.contentView addSubview:bgView];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"----点击");
    //删除模态视图
    [self dismissViewControllerAnimated:YES completion:nil];
    
    _bgView.hidden = YES;
    _addressCollectionView.hidden = NO;
    self.returnText = _searchList[indexPath.row];
    NSLog(@"text---%@",_returnText);
    
//    _textField.placeholder = @" ";
//    _textField.text = _returnText;
}

#pragma mark - UISearchResultsUpdating Method
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;
{
    searchBar.showsCancelButton = YES;
    UIButton *btn=[searchBar valueForKey:@"_cancelButton"];
    [btn setTitle:@"取消" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar __TVOS_PROHIBITED
{
    //删除模态视图
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark 监听者搜索框中的值的变化
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    // 1. 获取输入的值
    NSString *conditionStr = searchController.searchBar.text;
    
    if (searchController.searchBar.text.length > 0) {
        
        // 2. 创建谓词，准备进行判断的工具（[cd]其中[]中的c的意思是忽略字母的大小写,d是跟字母的重音有关。）˜
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self CONTAINS [CD] %@",conditionStr];
        
        // 3. 使用工具获取匹配出的结果
        self.searchList = [NSMutableArray arrayWithArray:[self.dataList filteredArrayUsingPredicate:predicate]];
        NSLog(@"%@",_searchList);
        
        if (_searchList.count != 0) {
            _searchTableViewController.tableView.userInteractionEnabled = YES;
            // 4. 刷新页面，将结果显示出来
            [_searchTableViewController.tableView reloadData];
        }else{
            _searchTableViewController.tableView.userInteractionEnabled = NO;
        }
    }
    
}
#pragma mark - 按钮点击事件
- (void)handleBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

//产生3个随机字母
- (NSString *)shuffledAlphabet {
    NSMutableArray * shuffledAlphabet = [NSMutableArray arrayWithArray:@[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"]];
    
    NSString *strTest = [[NSString alloc]init];
    for (int i=0; i<3; i++) {
        int x = arc4random() % 25;
        strTest = [NSString stringWithFormat:@"%@%@",strTest,shuffledAlphabet[x]];
    }
    return strTest;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end











